<?php

if( !defined( 'MEDIAWIKI' ) )
	die(-1);

require_once('DatabaseFunctions.php');

#install extension hook
$wgHooks['BeforePageDisplay'][] = "wfArtistOfTheDay";

function wfArtistOfTheDay()
{
  global $wgCategory, $wgTitle, $wgOut;
  wfProfileIn("wfArtistOfTheDay");

  $artistOfTheDay = getArtistOfTheDay(0);
  $wgOut->setArtistDay($artistOfTheDay);

  if ($wgCategory>0) {
  	$artistOfTheDay = getArtistOfTheDay($wgCategory);
	if ($artistOfTheDay==".") {
		wfProfileOut("wfArtistOfTheDay");
		return true;
	}
  }

  if ($wgTitle->mNamespace==NS_CATEGORY) {
	$wgOut->setOrder(-90);
	$wgOut->switchBocataMode(true);
  	$out .= '<div id="real-content"><div id="artistoftheday">';
  	$out .= '<h2>'.wfMsg( 'artist_of_the_day' ).'</h2>';
	$out .= getArtistInfo($artistOfTheDay).'<br>';
  	$out .= '</div></div>';
	$wgOut->addHTML($out);
        $wgOut->switchBocataMode(false);
	$wgOut->resetOrder();
  }
  wfProfileOut("wfArtistOfTheDay");

  return true;
}

function getArtistOfTheDay($wgCategory) {
  global $wgMemc;
  wfProfileIn("getArtistOfTheDay");
  $dbr = wfGetDB( DB_SLAVE );
  if ($wgCategory>0) $genreKey = "filter=genreKey,$wgCategory;";
  $artistOfTheDay = $wgMemc->get("artist$wgCategory"); 
  if (strlen($artistOfTheDay)==0)
  {
    $res = $dbr->query("SELECT VARIABLE_VALUE FROM INFORMATION_SCHEMA.SESSION_STATUS WHERE VARIABLE_NAME = 'SPHINX_TOTAL_FOUND' and (select count(id) from searches where query='$genreKey;limit=1') = 1;");
    if ($row = $dbr->fetchRow($res))
	$count = $row[0];
    else
	$count = 0;
    $dbr->freeResult( $res );
    if ($count>0) {
      $choosen = mt_rand(0,min(1000, $count*0.1));
      $res = $dbr->query("select artistkey from ss_tags t inner join searches s on s.idtags=t.idtags where query='groupby=attr:artistKey;select=idtags as idtags, sum(10/firstSeen*weightTags*TotalCount) as Count;groupsort=Count desc;offset=$choosen;limit=1;maxmatches=100000;$genreKey;floatrange=weightTags,0.6,1;sort=expr:1000/(CountFiles*weightTags+1);filter=type,1'");
      $row = $dbr->fetchRow($res);
	$artistOfTheDay = $row[0];
	$dbr->freeResult( $res );
	
	$sql = "select common_string(10, 150, Artist) as Artist from ss_tags where artistKey='$artistOfTheDay' group by artistKey;";
	$res = $dbr->query( $sql );
	$row = $dbr->fetchRow( $res );
    	$artistOfTheDay = $row[0];
       	$dbr->freeResult( $res );
    } else {
        $artistOfTheDay = ".";
    }
    $wgMemc->set("artist$wgCategory", $artistOfTheDay, 86400); //expires on one day
  }
  wfProfileOut("getArtistOfTheDay");

  return $artistOfTheDay;
}
